<template>
  <c-view>
    <template v-slot:header>
      <div class="title">
        {{ $route.meta.title }}
      </div>
    </template>
    <div class="main__box">
      <c-table
        ref="cTable"
        selection
        hasBorder
        :max-height="maxHeight"
        :size="size"
        :loading="isLoading"
        :table-header="tableHeader"
        :table-list="tableList"
        :table-inner-btns="tableInnerBtns"
        :page-info="pageInfo"
        @change-pagination="changePagination"
        @single-handle="changeSingleHandle"
      >
        <template v-slot:header>
          <c-search :form-model="searchObj" :form-items="searchItems" @submit-form="searchSubmit" @reset-form="searchReset">
            <!-- <template v-slot:btn>
              <el-button :size="size" type="primary">车辆超时无订单</el-button>
            </template> -->
          </c-search>
          <el-button-group class="btn-group">
            <el-button type="primary" @click="showParkDialog(0)">设置投放网点</el-button>
            <el-button type="primary" @click="showParkDialog(1)">设置还车网点</el-button>
            <el-button type="primary" @click="showDispatcherDialog()">设置调度员</el-button>
            <el-button type="primary" @click="showCarMap(2)">地图查看</el-button>
            <!-- <el-button type="primary" @click="orderCar">预约车辆</el-button> -->
            <el-button type="primary" @click="showCarMap(3)">车辆轨迹</el-button>
          </el-button-group>
          <el-button-group class="btn-group">
            <el-button type="primary" v-for="(item, index) in operateBtns" :key="index" :loading="item.loading" @click="doOperate(item.type, index)">
              {{ item.name }}
            </el-button>
          </el-button-group>
        </template>
      </c-table>
    </div>
    <div v-if="dialogObj.isShow">
      <c-dialog
        width="80%"
        :class="dialogObj.type === 1 ? 'dialog-box' : ''"
        :fullscreen="dialogObj.type !== 1 && dialogObj.type !== 4"
        :is-show="dialogObj.isShow"
        :title="dialogObj.title"
        close-btn
        :no-btn="dialogObj.noBtn"
        @before-close="dialogObj.isShow = false"
        @on-submit="dialogConfirm"
      >
        <park-add v-if="dialogObj.type === 1 || dialogObj.type === 0" ref="childRef" :init-data.sync="dialogObj.initData"></park-add>
        <review-map v-if="dialogObj.type === 2" ref="childRef" :init-data.sync="dialogObj.initData"></review-map>
        <map-track v-if="dialogObj.type === 3" ref="childRef" :init-data.sync="dialogObj.initData"></map-track>
        <dispatcher-add v-if="dialogObj.type === 4" ref="childRef" :init-data.sync="dialogObj.initData"></dispatcher-add>
      </c-dialog>
    </div>
  </c-view>
</template>

<script>
import mixinTable from 'mixins/table'
import CDialog from 'components/dialog'
import dictObj from '@/store/dictData'
import ParkAdd from './park-add'
import ReviewMap from './review-map'
import MapTrack from './map-track'
import dispatcherAdd from './dispatcher-add'

export default {
  name: 'carOperate',
  mixins: [mixinTable],
  components: {
    CDialog,
    ParkAdd,
    ReviewMap,
    MapTrack,
    dispatcherAdd
  },
  data(vm) {
    return {
      operateBtns: [
        {
          type: 'findCar',
          loading: false,
          name: '鸣笛'
        },
        {
          type: 'openDoor',
          loading: false,
          name: '开锁'
        },
        {
          type: 'closeDoor',
          loading: false,
          name: '关锁'
        },
        {
          type: 'powerOn',
          loading: false,
          name: '通电'
        },
        {
          type: 'powerOff',
          loading: false,
          name: '断电'
        },
        {
          type: 'queryCarStatus',
          loading: false,
          name: '刷新车辆'
        },
        {
          type: 'setPassword',
          loading: false,
          name: '设置密码'
        }
      ],
      carInfo: null, // 选中当前车辆信息
      // 对话框对象
      dialogObj: {},
      // 表格内操作按钮
      tableInnerBtns: [
        {
          name: '车辆图片',
          icon: 'el-icon-view',
          width: 100,
          handle(row) {
            const { carNumber } = row
            vm.routerLink(`/vehicle/operate/review/${carNumber}`)
          }
        }
      ],
      tableHeader: [
        {
          label: '车牌号码',
          prop: 'carNumber',
          fixed: true,
          search: {
            type: 'input'
          }
        },
        {
          label: '所属企业',
          prop: 'companyName'
        },
        {
          label: '车辆状态',
          prop: 'carRunStatus',
          formatter: row => (row && dictObj.carOperateStatus[row.carRunStatus] ? dictObj.carOperateStatus[row.carRunStatus].name : row.carRunStatus),
          search: {
            type: 'dict',
            prop: 'status',
            optionsList: dictObj.searchOperateStatusList
          }
        },
        {
          label: '是否在线',
          prop: 'isOnline',
          formatter: row => (new Date().getTime() - new Date(row.updateTime).getTime() > 15 * 60 * 1000 || !row.updateTime ? '离线' : '在线')
        },
        {
          label: '剩余电量/油量(%)',
          prop: 'restBattery',
          width: 140,
          setColor: row => (row.restBattery < 30 ? 'red' : row.restBattery > 70 ? 'green' : 'yellow')
        },
        {
          label: '小电瓶电压(V)',
          prop: 'smallBatteryVoltage',
          width: 120,
          setColor: row => (row.smallBatteryVoltage < 10 ? 'red' : 'green')
        },
        {
          label: '车辆密码',
          prop: 'carPassword',
          isPopover: true,
          setColor: () => 'blue',
          formatter: () => '查看密码'
        },
        {
          label: '车门状态',
          prop: 'doorStatus',
          formatter: row => row && vm.setTableColumnLabel(row.doorStatus, 'doorStatus')
        },
        {
          label: '发动机状态',
          prop: 'carSignal',
          setColor: row => (row && row.carSignal === '1' ? 'green' : ''),
          formatter: row => (row && row.carSignal === '1' ? '启动' : '熄火')
        },
        {
          label: '锁定状态',
          prop: 'isLockCar',
          setColor: row => (row && row.isLockCar === 1 ? 'red' : ''),
          formatter: row => (row && row.isLockCar === 1 ? '已锁定' : '未锁定')
        },
        {
          label: '投放网点',
          prop: 'parkName',
          search: {
            type: 'input'
          }
        },
        {
          label: '还车网点',
          prop: 'returnCarParkName'
        },
        {
          label: '车门状态',
          prop: 'doorStatus',
          formatter: row => (row.doorStatus === '0' ? '关门' : row.doorStatus === '1' ? '开门' : '')
        },
        {
          label: '设备最后上报时间',
          prop: 'updateTime',
          width: 160
        },
        {
          label: '剩余续航(KM)',
          prop: 'enduranceMileage',
          width: 110
        },
        {
          label: '行驶总里程(KM)',
          prop: 'mileage',
          width: 130
        },
        {
          label: '所属城市',
          prop: 'cityName'
        },
        {
          label: '车辆图片',
          prop: 'smallCarImgurl',
          isImage: true
        },
        {
          label: '车辆品牌',
          prop: 'brandName'
        },
        {
          label: '车辆型号',
          prop: 'carTypeTypeName'
        },
        {
          label: '车身颜色',
          prop: 'color'
        },
        {
          label: '设备编号',
          prop: 'cid'
        },
        {
          label: '发动机号',
          prop: 'engineno',
          width: 120
        },
        {
          label: '车架号',
          prop: 'classno',
          width: 170
        },
        {
          label: 'SIM卡号',
          prop: 'phone',
          width: 110
        }
      ]
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    /*
     * 查询表格列表数据
     */
    fetchData() {
      const { pageNo, pageSize } = this.pageInfo
      const { dateTime, ...other } = this.searchObj
      const searchDate = this.getSearchDate(dateTime)
      this.isLoading = true
      this.$api.vehicle
        .fetch('carMrgRunList', {
          ...searchDate,
          ...other,
          rows: pageNo,
          offset: pageSize
        })
        .then(res => {
          this.isLoading = false
          if (res && res.totalCount) {
            const { data, totalCount } = res
            this.pageInfo.totalNum = totalCount
            this.tableList = data || []
          } else {
            this.tableList = res || []
          }
        })
    },
    /**
     * dialog对话框数据处理
     * @opts {*}
     */
    showDialog(opts) {
      this.dialogObj = {
        isShow: true,
        isEdit: opts.isEdit || false,
        noBtn: opts.noBtn,
        type: opts.type,
        title: opts.title || '设置网点',
        initData: opts.initData
      }
    },
    /**
     * dialog新增、编辑处理函数
     */
    dialogConfirm() {
      const { curParkInfo, initData, dispatcherIds } = this.$refs.childRef
      if (this.dialogObj.type === 1 || this.dialogObj.type === 0) {
        if (this.dialogObj.type === 0) {
          this.$api.vehicle
            .fetch('saveParkInfo', {
              parkId: curParkInfo.id,
              id: initData.id
            })
            .then(() => {
              this.responeHandle('设置投放网点成功')
            })
        } else {
          const { carNumber } = this.carInfo
          this.$api.vehicle
            .fetch('setReturnCarPark', {
              parkId: curParkInfo.id,
              carNumber
            })
            .then(() => {
              this.responeHandle('设置还车网点成功')
            })
        }
      } else if (this.dialogObj.type === 4) {
        const { carNumber } = this.carInfo
        // if (!dispatcherIds || !dispatcherIds.length) {
        //   return this.$msgTip('请先选中调度员', 'warning')
        // }
        this.$api.vehicle
          .fetch('setDispatcher', {
            carNumber,
            dispatcherIds
          })
          .then(() => {
            this.responeHandle('调度员设置成功')
          })
      }
    },
    showParkDialog(type) {
      if (this.carInfo) {
        const { carRunId, carNumber, parkName, returnCarParkName } = this.carInfo
        if (!carNumber || !carRunId) {
          return this.$msgTip('请先选择车辆', 'warning')
        }
        this.showDialog({
          isShow: true,
          type,
          title: type === 0 ? `设置投放网点（${carNumber}）` : `设置还车网点（${carNumber}）`,
          noBtn: false,
          initData: {
            type,
            id: carRunId,
            parkName,
            returnCarParkName
          }
        })
      } else {
        this.$msgTip('请先选择车辆', 'warning')
      }
    },
    showDispatcherDialog() {
      if (this.carInfo) {
        const { carRunId, carNumber } = this.carInfo
        if (!carNumber || !carRunId) {
          return this.$msgTip('请先选择车辆', 'warning')
        }
        this.showDialog({
          isShow: true,
          type: 4,
          title: `设置调度员（${carNumber}）`,
          noBtn: false,
          initData: {
            carNumber
          }
        })
      } else {
        this.$msgTip('请先选择车辆', 'warning')
      }
    },
    showCarMap(type) {
      if (this.carInfo) {
        const { carNumber, carRunLongitude, carRunLatitude } = this.carInfo
        if (!carNumber) {
          return this.$msgTip('请先选择车辆', 'warning')
        }
        if (!carRunLongitude || !carRunLatitude) {
          return this.$msgTip('暂无车辆位置信息', 'warning')
        }
        this.showDialog({
          isShow: true,
          type,
          noBtn: true,
          title: type === 2 ? `查看车辆位置（${carNumber}）` : `查看车辆轨迹（${carNumber}）`,
          initData: this.carInfo
        })
      } else {
        this.$msgTip('请先选择车辆', 'warning')
      }
    },
    orderCar() {
      // const { carNumber } = this.carInfo
      // const { memberPhone, isInsurance } = this.dialogObj.initData
      // this.$api.vehicle.fetch('orderCar', { memberPhone, carNumber, isInsurance }).then(() => {
      //   this.responeHandle('预约车辆成功')
      // })
    },
    doOperate(operateType, index) {
      if (!this.carInfo) {
        return this.$msgTip('请先选择车辆', 'warning')
      }
      const { carNumber } = this.carInfo
      this.operateBtns[index].loading = true
      const { userName } = this.$store.getters
      this.$api.vehicle.fetch('openTheDoor', { operateType, carNumber, dispatcherName: userName }, { hasErrMsg: true }).then(res => {
        const { code, message } = res
        if (code === 0) {
          this.$msgTip(`${dictObj.carOperateType[operateType]}成功`)
          if (operateType === 'queryCarStatus' || operateType === 'setPassword') {
            this.fetchData()
          }
        } else {
          this.$msgTip(message, 'warning')
        }
        this.operateBtns[index].loading = false
      })
    },
    changeSingleHandle(item) {
      this.carInfo = item
    }
  }
}
</script>
